﻿<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ContactProfile.ascx.cs" Inherits="CRMWeb.UserControls.ContactProfile" %>
<div id="contactprofile" style="background-color: rgb(224,255,193);">
    <div class="top_section" style="vertical-align: middle">
        <table style="width: 100%">
            <tr>
                <td style="text-align: left; width: 20%">
                    <span id="spnNavigation"></span>
                </td>
                <td style="text-align: left; width: 30%">
                    <span id="spnAppTitle" style="width: auto; text-align: center">

                        <label id="lblfirstName" style="font-weight: bold; font-family: Arial; font-size: 14px;"></label>

                        <label id="lbllastName" runat="server" style="font-weight: bold; font-family: Arial; font-size: 14px;"></label>

                        <b>'s Client Profile </b>
                    </span>
                </td>
                <td style="text-align: center; width: 50%">
                    <a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-ok" onclick="saveContact()">Save</a>
                    <a id="lnkaddClient" href="/Pages/Contact/ContactDetail.aspx" class="easyui-linkbutton" iconcls="icon-add">Add New Client</a>
                    <a id="lnkaddApp" href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-add" onclick="addNewApplication()">Add New App</a>
                    <a id="lnkRemoveDup" href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-remove" onclick="OpenRemoveDupDialog()">Remove Dup</a>
                    <a id="lnkDelete" href="javascript:void(0)" class="easyui-linkbutton" onclick="$('#dlgDeleteConfirm').dialog('open')" plain="true" iconcls="icon-cancel" title="Delete Client"></a>
                </td>
            </tr>
        </table>
    </div>
    <div class="topform_section">
        <div>
            <div class="fitem">
                <label style="width: 120px;">Full Name:</label>
                <select id="cmbTitle" data-options="panelHeight:'auto'" class="easyui-combobox" name="Title" style="width: 70px;">
                    <option value="">-Select-</option>
                    <option value="Mr">Mr</option>
                    <option value="Ms">Ms</option>
                    <option value="Miss">Miss</option>
                    <option value="Mrs">Mrs</option>
                    <option value="Dr">Dr</option>
                    <option value="Other">Other</option>
                </select>
                <input id="txtFullName" name="FullName" type="text" style="width: 200px; background-color: LightGray;" readonly="true" />
                <a href="javascript:void(0)" class="easyui-linkbutton" onclick="$('#dlgFullName').dialog('open')">...</a>

                <div id="imgduplicate" style="float: right; width: 200px; display: none">
                    <a id='lnkDuplicate' href="javascript:void(0)" onclick="OpenDialogDuplicate()" style="float: left">
                        <img id=" imageDuplicate" src="../../Media/duplicate.jpg" />
                    </a>
                </div>
            </div>
        </div>
        <div class="firstform_section">
            <div class="fitem">
                <label>Primary Email:</label>
                <input id="txtEmail" class="easyui-validatebox" style="width: 180px" onchange="CheckEmail($('#txtEmail').val(),1)" />
                <span id="spnemail1" style="display: none; color: red">* </span>
            </div>
            <div class="fitem">
                <label>Secondary Email:</label>
                <input id="txtEmail2" class="easyui-validatebox" style="width: 180px" onchange="CheckEmail($('#txtEmail2').val(),2)" />
                <span id="spnemail2" style="display: none; color: red">* </span>

            </div>
            <div class="fitem">
                <label>Mobile:</label>

                <input id="txtMobile" type="text"  />
            </div>
            <div class="fitem">
                <label>Home:</label>
                <input id="txtHomePhone" type="text" onkeyup="CheckAreaCode(this.value, event)" />

            </div>
            <div class="fitem">
                <label>DOB:</label>
                <%-- <input id="txtDateBirth" name="DateBirth" class="easyui-datebox" type="text" data-options="formatter:format_Date" style="width: 100px;" />
                --%>
                <input id="txtDateBirth" name="DateBirth" class="easyui-datebox" type="text" data-options="formatter:au_formatter,parser:au_parser" style="width: 100px;" />

                <input id="txtAge" type="text" readonly="true" style="background-color: LightGray; width: 80px;" />

            </div>
            <div class="fitem">
                <label>Driver Licence:</label>
                <input id="txtDriverLicense" type="text" name="DriverLicense" class="easyui-validatebox" />
            </div>
            <div class="fitem">
                <label>Citizenship:</label>
                <select id="cmbResidency" data-options="panelHeight:'auto'" class="easyui-combobox" name="Citizenship" style="width: 190px;">
                    <option selected="selected" value="">-Select-</option>
                    <option value="New Zealand - Born in New Zealand">New Zealand - Born in New Zealand</option>
                    <option value="New Zealand - Born overseas">New Zealand - Born overseas</option>
                    <option value="Permanent Resident (PR)">Permanent Resident (PR)</option>
                    <option value="Australia Citizen &amp; Australia PR">Australia Citizen &amp; Australia PR</option>
                    <option value="Working Visa">Working Visa</option>
                    <option value="Others">Others</option>
                </select>
            </div>
            <div class="fitem">
                <label>Create Date:</label>
                <input id="createDate" type="text" readonly="true" style="background-color: LightGray; width: 185px;" />
            </div>
        </div>
        <div class="firstform_section">
            <div class="fitem">
                <label>Street:</label>
                <input id="txtStreetNo" type="text" class="easyui-validatebox" style="width: 55px">
                <input id="txtStreet" name="Street" type="text" class="easyui-validatebox" style="width: 120px" />
            </div>
            <div class="fitem">
                <label>Suburb:</label>
                <input id="txtSuburb" name="Suburb" type="text" class="easyui-validatebox" />
            </div>
            <div class="fitem">
                <label>Region/ Postcode:</label>
                <select id="cmbState" data-options="panelHeight:'150',panelWidth:'150'" style="width: 90px;" class="easyui-combobox" name="State">
                    <option value="">-Select-</option>
                    <option value="Auckland">Auckland</option>
                    <option value="Wellington">Wellington</option>
                    <option value="Christchurch">Christchurch</option>
                    <option value="Hamilton">Hamilton</option>
                    <option value="Napier-Hastings">Napier-Hastings</option>
                    <option value="Tauranga">Tauranga</option>
                    <option value="Dunedin">Dunedin</option>
                    <option value="Palmerston North">Palmerston North</option>
                    <option value="Nelson">Nelson</option>
                    <option value="Rotorua">Rotorua</option>
                    <option value="New Plymouth">New Plymouth</option>
                    <option value="Whengarei">Whengarei</option>
                    <option value="Invercargill">Invercargill</option>
                    <option value="Whanganui(Wanganui)">Whanganui(Wanganui)</option>
                    <option value="Gisborne">Gisborne</option>
                </select>
                <input id="txtPostCode" type="text" class="easyui-validatebox" style="width: 92px;" />
            </div>
            <div class="fitem">
                <label>Residential Status:</label>
                <select id="cmbResidentialStatus" data-options="panelHeight:'auto'" class="easyui-combobox" style="width: 190px;" name="app_ResidentialStatus">
                    <option value="">-Select-</option>
                    <option value="I own my home outright">I own my home outright</option>
                    <option value="I have a mortgage">I have a mortgage</option>
                    <option value="I am boarding">I am boarding</option>
                    <option value="I am renting">I am renting</option>
                </select>
            </div>
            <div class="fitem">
                <label>Length of Residence:</label>
                <select id="cmbResidencePeriod" data-options="panelHeight:'auto'" style="width: 90px;" class="easyui-combobox" name="ResidencePeriod">
                    <option value="Year/s">Year/s</option>
                    <option value="Month/s">Month/s</option>
                </select>
                <input id="txtResidenceLength" name="ResidenceLength" type="text" class="easyui-validatebox" style="width: 92px;" />
            </div>
            <div class="fitem">
                <label>No of Dependant:</label>
                <select id="cmbNumberofDependant" data-options="panelHeight:'auto'" style="width: 90px;" class="easyui-combobox" name="Dependant">
                    <option value="0">0</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                </select>
                <span>Under 18</span>
            </div>
            <div class="fitem">
                <label>Unsubscribe Ad:</label>
                <input type="checkbox" id="checkUnsub" value="" />
            </div>

            <div class="fitem">
                <span id="spnDupwith" style="display: none"></span>
                <span id="spnDeleted" style="display: none">
                    <label>Deleted Flag:</label>
                    <label style="color: red">Deleted </label>
                </span>
            </div>
        </div>
        <div class="firstform_section">
            <div class="fitem">
                <label>Memo:</label>
            </div>
            <textarea id="txtMemo" name="Memo" onkeydown="setFocus('Memo')" onclick="memoEdited()" style="font-family: Arial,Helvetica,sans-serif; width: 100%; height: 140px; margin-bottom: 10px"></textarea>
            <div>
                <span id="spnSageContact" style="display: none">
                    <label style="width: auto; color: red"><b>Please track this client in Sage System </b></label>
                </span>
            </div>
        </div>
    </div>
    <div id="dlgFullName" title="Fullname Information" class="easyui-dialog" style="width: 300px; height: 200px; padding: 10px" closed="true" buttons="#dlgFullName-buttons">
        <div class="fitem">
            <label style="width: 120px;">First Name:</label>
            <input id="txtFirstName" type="text" onkeydown="setFocus('MiddleName')" name="FirstName" class="easyui-validatebox" />
        </div>
        <div class="fitem">
            <label style="width: 120px;">Middle Name:</label>
            <input id="txtMiddleName" type="text" onkeydown="setFocus('SurName')" name="MiddleName" class="easyui-validatebox" />
        </div>
        <div class="fitem">
            <label style="width: 120px;">Surname:</label>
            <input id="txtSurName" name="SurName" onkeydown="setFocus('Save')" type="text" class="easyui-validatebox" />
        </div>
        <div id="dlgFullName-buttons">
            <a href="javascript:void(0)" class="easyui-linkbutton" onclick="setFullName()">Save</a>
        </div>
    </div>
    <div id="dlgRemoveDuplicate" title="Remove Duplicate Client" class="easyui-dialog" style="width: 400px; height: auto; padding: 10px" closed="true">
        <div style="text-align: center">
            <label style="width: auto; padding-top: 5px; font-weight: bold">Remove Duplicate Client </label>
        </div>
        <br />
        <table style="width: 100%">
            <tr>
                <td style="text-align: right">
                    <label style="width: 120px; font-weight: bold">Current Client ID : </label>
                </td>
                <td style="text-align: left">
                    <label id="lblcurrentContactID" style="color: red"></label>
                </td>
            </tr>
            <tr>
                <td style="text-align: right">
                    <label style="width: 120px; font-weight: bold">New Client ID : </label>
                </td>
                <td style="text-align: left">
                    <input id="txtNewContactId" class="easyui-validatebox" type="text" />
                </td>
            </tr>
            <tr>
                <td style="text-align: right"></td>
                <td style="text-align: left">
                    <a href="javascript:void(0)" class="easyui-linkbutton" onclick="RemoveDuplicate()">Save</a>
                </td>
            </tr>
        </table>
    </div>
    <div id="dlgDeleteConfirm" class="easyui-dialog" title="Confirm" style="width: 300px; height: 160px" closed="true" resizable="false" modal="true">
        <h4 style="text-align: center">Are you sure to delete this client ?</h4>
        <div class="fitem" style="float: left; padding: 10px; margin-top: 10px">
            <a id="lnkDeleteApplication" href="javascript:void(0)" class="easyui-linkbutton" onclick="deleteClient()" disabled="true">OK</a>
            <a id="lnkCancle" href="javascript:void(0)" class="easyui-linkbutton" onclick="$('#dlgDeleteConfirm').dialog('close')" disabled="true">Cancel</a>
            <span id="spnanimate">
                <img id="deleteProgress" style="margin-left: 20px" src="../../Media/loading.gif" />
                <label id="lbltimeOut" style="margin-left: 20px">5</label>
            </span>
        </div>
    </div>
    <div id="dlgSuccess" class="easyui-dialog" title="Success" style="width: 300px; height: 120px" closed="true" resizable="false" modal="true">
        <h4 style="text-align: center">Application contact save successfully</h4>
        <img id="successProgress" style="margin-left: 20px" src="../../Media/loading.gif" />
        <label id="lblSuccessTimeOut" style="margin-left: 20px">5</label>
    </div>
</div>

<script type="text/javascript">


   

    function showPrompt() {
        return 'You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?';
    }
    var isMemoedited = false;
    var isValidated = true;
    function memoEdited() {
        isMemoedited = true;
        window.onbeforeunload = showPrompt;
    }
    function setFocus(control) {
        document.onkeypress = function chekKey(e) {
            e = e || window.event;
            if (e.keyCode == '13')// Enter Key
            {
                if (control == 'MiddleName')
                    $('#txtMiddleName').focus();
                else if (control == 'SurName')
                    $('#txtSurName').focus();
                else if (control == 'Save')
                    setFullName();
                else if (control == 'Memo') { }
            }
        }
    }


    function popupWinCenter(URL, title, w, h) {
        var left = (screen.width / 2) - (w / 2);
        var top = (screen.height / 2) - (h / 2);
        var strfeatures = 'width=' + w + ', height= ' + h + ', top=' + top + ',left=' + left;
        var newWin = window.open(URL, title, strfeatures);
        newWin.onload = function () { window.focus(); }
        newWin.onunload = function () { $('#dgContactHistory').datagrid('reload'); }
    }
    function deleteClient() {
        var currentClientID = getQuerystring('contact_id', '');
        $.ajax({
            url: '/WebServices/ApplicationContact.ashx?method=DeleteClient',
            data: { ContactID: currentClientID },
            success: function (rec) {
                // insert to Contact_history

                var desc = ' This Client is deleted = ' + currentClientID;
                var currentDate = new Date();
                var HistoryDate = currentDate.getMonth() + 1 + "/" + currentDate.getDate() + "/" + currentDate.getFullYear();

                var currentTime = new Date();
                var HistoryTime = currentTime.getHours() + ':' + currentTime.getMinutes() + ':' + currentTime.getSeconds();;
                var Action = 'Client Deleted (System)';
                var Operator = $('#ContentPlaceHolder1_hdnusername').val();

                $.ajax({
                    url: "/WebServices/History.ashx?method=saveNewHistory",
                    data: {
                        HistoryType: 'Contact', contactid: currentClientID, hdate: HistoryDate, htime: HistoryTime, action: Action,
                        user: Operator, description: desc, appid: '0'
                    },
                    success: function (result) {
                        window.location.href = '/Pages/Contact/ContactList.aspx';
                    }
                });

            }
        });
    }
    function enableWindowUnload() {
        $(".firstform_section :text").on("change", function () {
            $('#lnkaddApp').linkbutton('disable');
            $('#lnkaddClient').linkbutton('disable');
            window.onbeforeunload = showPrompt;
        });
        $('#cmbTitle').combobox({
            onSelect: function (n, o) {
                $('#lnkaddApp').linkbutton('disable');
                $('#lnkaddClient').linkbutton('disable');
                window.onbeforeunload = showPrompt;
            }
        });
        $('#cmbResidency').combobox({
            onSelect: function (n, o) {
                $('#lnkaddApp').linkbutton('disable');
                $('#lnkaddClient').linkbutton('disable');
                window.onbeforeunload = showPrompt;
            }
        });
        $('#cmbState').combobox({
            onSelect: function (n, o) {
                $('#lnkaddApp').linkbutton('disable');
                $('#lnkaddClient').linkbutton('disable');
                window.onbeforeunload = showPrompt;
            }
        });
        $('#cmbResidentialStatus').combobox({
            onSelect: function (n, o) {
                $('#lnkaddApp').linkbutton('disable');
                $('#lnkaddClient').linkbutton('disable');
                window.onbeforeunload = showPrompt;
            }
        });
        $('#cmbResidencePeriod').combobox({
            onSelect: function (n, o) {
                $('#lnkaddApp').linkbutton('disable');
                $('#lnkaddClient').linkbutton('disable');
                window.onbeforeunload = showPrompt;
            }
        });
        $('#cmbNumberofDependant').combobox({
            onSelect: function (n, o) {
                $('#lnkaddApp').linkbutton('disable');
                $('#lnkaddClient').linkbutton('disable');
                window.onbeforeunload = showPrompt;
            }
        });
        $('#checkUnsub').change(function () {
            window.onbeforeunload = showPrompt;
        });
        $('#txtDateBirth').datebox({
            onSelect: function (date) {
                $('#lnkaddApp').linkbutton('disable');
                $('#lnkaddClient').linkbutton('disable');
                $('#txtAge').val(ageCalculation(date) + ' years old');
                window.onbeforeunload = showPrompt;

                var temp = DefaultformatDate($('#txtDateBirth').datebox('getValue'));
                var date_arr = temp.split('/');
                var calObj = $('#txtDateBirth').datebox('calendar');
                calObj.calendar('moveTo', new Date(date_arr[2], date_arr[0] - 1, date_arr[1]));

            }
        });
    }
    $('#txtSurName').keyup(function () {
        $(this).val($(this).val().toUpperCase());
    });


    function startCounter(limit) {
        setTimeout(function () {
            if (limit == 0) {
                $('#dlgDeleteConfirm').dialog('close');
                $('#lnkDeleteApplication').linkbutton('enable');
                $('#lnkCancle').linkbutton('enable');
                $('#spnanimate').hide();
            }
            else {
                $('#lbltimeOut').html(limit);
                startCounter(limit - 1);
            }
        }, 100);
    }

    function startSuccessCounter(limit) {
        setTimeout(function () {
            if (limit == 0) {
                $('#dlgSuccess').dialog('close');
            }
            else {
                $('#lblSuccessTimeOut').html(limit);
                startSuccessCounter(limit - 1);
            }
        }, 100);
    }

    $(document).keydown(function (event) {
        if ((event.which == 83 || event.which == 115) && (event.ctrlKey || event.metaKey) || (event.which == 19)) {
            event.preventDefault();
            saveContact();
            return false;
        }
        else if ((event.which == 72 || event.which == 104) && (event.ctrlKey || event.metaKey) || (event.which == 19)) {
            event.preventDefault();
            // do stuff - ctrl + h
            setTimeout(function () {
                popupWinCenter('/Pages/History.aspx?type=Contact&Operation=new&contactid=' + getQuerystring('contact_id', ''), 'New Contact history', 650, 600);
            }, 100);
            return false;
        }
        return true;
    });

    $(document).ready(function () {
        $('#dlgDeleteConfirm').dialog({
            onOpen: function () {
                startCounter(5);
            },
            onClose: function () {
                $('#lnkDeleteApplication').linkbutton('disable');
                $('#lnkCancle').linkbutton('disable');
                $('#spnanimate').show();
                $('#lbltimeOut').html('');
            }
        });

        $('#dlgSuccess').dialog({
            onOpen: function () {
                startSuccessCounter(5);
            },
            onClose: function () {
                $('#lblSuccessTimeOut').html('');
            }
        });






        jQuery(function ($) {
            $('#txtMobile').mask("?9999 999 9999");
            $('#txtHomePhone').mask("?99 999 9999");
            $('#txtPostCode').mask("?9999");
        });


       
        bindClientDetail();
        getNavigation();
        if (getQuerystring('contact_id', '') == '') {
            $('#lnkaddClient').hide();
        }

        enableWindowUnload();
        fnLeftNavSelected('A13');

        $('#cmbTitle').combobox('textbox').bind('click', function () {
            $('#cmbTitle').combobox('showPanel');
        });
        $('#cmbResidency').combobox('textbox').bind('click', function () {
            $('#cmbResidency').combobox('showPanel');
        });
        $('#cmbState').combobox('textbox').bind('click', function () {
            $('#cmbState').combobox('showPanel');
        });
        $('#cmbResidentialStatus').combobox('textbox').bind('click', function () {
            $('#cmbResidentialStatus').combobox('showPanel');
        });

        $('#cmbResidencePeriod').combobox('textbox').bind('click', function () {
            $('#cmbResidencePeriod').combobox('showPanel');
        });
        $('#cmbNumberofDependant').combobox('textbox').bind('click', function () {
            $('#cmbNumberofDependant').combobox('showPanel');
        });
    });

    function OpenDuplicateCilentProfile(DupwithContact) {
        var newTab = window.open("/Pages/Contact/ContactDetail.aspx?contact_id=" + DupwithContact, '_blank');
    }

    function PopupWindowCenter(URL, title, w, h) {
        var left = (screen.width / 2) - (w / 2);
        var top = (screen.height / 2) - (h / 2);
        var strfeatures = 'width=' + w + ', height= ' + h + ', top=' + top + ',left=' + left;
        var newWin = window.open(URL, title, strfeatures);
    }

    function validateEmail(elementValue) {
        if (elementValue.length > 0) {
            var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
            if (emailPattern.test(elementValue) == false)
                return false;
            else
                return true;
        }
        else
            return true;
    }

    function CheckEmail(elementValue, eleNo) {
        if (elementValue.length > 0) {
            var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
            if (emailPattern.test(elementValue) == false) {
                if (eleNo == 1)
                    $('#spnemail1').show();
                else if (eleNo == 2)
                    $('#spnemail2').show();
            }
            else {
                if (eleNo == 1)
                    $('#spnemail1').hide();
                else if (eleNo == 2)
                    $('#spnemail2').hide();
            }
        }
        else {
            if (eleNo == 1)
                $('#spnemail1').hide();
            else if (eleNo == 2)
                $('#spnemail2').hide();
        }

    }


    //Function by Ashok Rathore to check area code:
    function CheckAreaCode(val, e) {
        var firstChar = val.charAt(0);
        var secondChar = val.charAt(1);
        if (firstChar != "_" && secondChar != "_") {
            var final = firstChar + secondChar;

            if (final.length == 2) {
                if (final == 09 || final == 03 || final == 04 || final == 06 || final == 07) {

                }
                else {
                    $.messager.alert('Morgan CRM', 'Only 03 04 06 07 09 allowed for area code');
                }


            }
        }
    }






    function bindClientDetail() {
        $.ajax({
            url: "/WebServices/ApplicationContact.ashx?method=SelectClientDetail",
            contentType: "application/json; charset=utf-8",
            data: { 'ContactID': getQuerystring('contact_id', '') },
            async: true,
            success: function (data) {
                $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {

                    var fname = rec.FirstName;
                    var middleName = rec.MiddleName;

                    if (middleName.length > 0) {
                        fname = fname + ' ' + middleName;
                    }
                    // var middleName = rec.MiddleName;
                    //!str || 0 === str.length
                    fname = fname.charAt(0).toUpperCase() + fname.slice(1);
                    var sname = rec.SurName;

                    $('#lblfirstName').html(fname);
                    $('#ContentPlaceHolder1_ContactProfile_lbllastName').html(sname.toUpperCase());

                    $('#txtContactID').numberbox('setValue', rec.ContactID);
                    $('#txtFullName').val(rec.FirstName + ' ' + rec.MiddleName + ' ' + rec.SurName);
                    $('#cmbTitle').combobox('setValue', rec.Title);
                    $('#txtFirstName').val(rec.FirstName);
                    $('#txtMiddleName').val(rec.MiddleName);
                    $('#txtSurName').val(rec.SurName);
                    $('#cmbResidency').combobox('setValue', rec.Citizenship);

                    $('#txtDateBirth').datebox('setValue', au_formatter(rec.DateBirth, null));
                    //COMMENT start --from Wade 11/10/2013
                    // $('#txtDateBirth').datebox('setValue', format_Date(rec.DateBirth, null));
                    //var temp = DefaultformatDate($('#txtDateBirth').datebox('getValue'));

                    //var date_arr = temp.split('/');
                    //var calObj = $('#txtDateBirth').datebox('calendar');
                    //calObj.calendar('moveTo', new Date(date_arr[2], date_arr[0] - 1, date_arr[1]));
                    //COMMENT end  --from Wade 11/10/2013

                    $('#txtDriverLicense').val(rec.DriverLicense);
                    $('#txtMobile').val(rec.Mobile);
                    //To set value for sms usercontrol mobileno.
                    if (rec.Mobile != '' && rec.Mobile != null) {
                        $('#txtmobno').numberbox('setValue', rec.Mobile);
                    }
                    $('#txtHomePhone').val(rec.HomePhone);
                    $('#txtEmail').val(rec.Email);
                    $('#txtEmail2').val(rec.secondEmailAddress);
                    $('#txtStreet').val(rec.Street);
                    $('#txtStreetNo').val(rec.StreetNo);
                    $('#txtSuburb').val(rec.Suburb);
                    $('#cmbState').combobox('setValue', rec.State);
                    if (rec.PostCode.indexOf('_') < 0) {
                        $('#txtPostCode').val(rec.PostCode);
                    }
                    $('#cmbResidentialStatus').combobox('setValue', rec.app_ResidentialStatus);
                    $('#cmbResidencePeriod').combobox('setValue', rec.ResidencePeriod);
                    $('#txtResidenceLength').val(rec.ResidenceLength);

                    if (rec.Unsubscribe_Ad == 1)
                        $('#checkUnsub').prop('checked', true);
                    else
                        $('#checkUnsub').prop('checked', false);

                    $('#cmbNumberofDependant').combobox('setValue', rec.Dependant);
                    $('#txtMemo').val(rec.Memo);
                    $('#createDate').val(rec.cdate);

                    if (rec.deletedFlag == 1)
                        $('#spnDeleted').show();
                    else
                        $('#spnDeleted').hide();

                    if (rec.comesfrom == 'SAGE')
                        $('#spnSageContact').show();
                    else
                        $('#spnSageContact').hide();

                    if (rec.DupwithContact > 0) {
                        $('#contactprofile').css('background-color', '#A9A9A9');
                        $('#spnDupwith').show();
                        $('#spnDupwith').html('<label>Duplicate With:</label>' +
                                              '<a id="lnkDupwith" href="#" onclick="OpenDuplicateCilentProfile(' + rec.DupwithContact + ')" >' + rec.DupwithContact + ' </a><br/>');
                    }
                    else {
                        $('#spnDupwith').hide();
                        if (rec.isDuplicate == 1) {
                            $('#imgduplicate').show();
                        }
                        else {
                            $('#imgduplicate').hide();
                        }
                    }
                });
            }
        });
    }
    function OpenDialogDuplicate() {
        var contactid = getQuerystring('contact_id', '');
        var w = window.innerWidth;
        var h = window.innerHeight;
        var strfeatures = 'width=' + w + ', height= ' + h;

        window.open('/Pages/Contact/CompareDuplicate.aspx?contact_id=' + contactid, ' Morgan CRM - Compare Duplicate ', strfeatures);
    }
    function getNavigation() {
        if (document.referrer.indexOf('ContactList.aspx') > 0)
            $('#spnNavigation').html('<a href="javascript: history.go(-1)">List</a> >> ');
        else if (document.referrer.indexOf('ApplicationDetail.aspx') > 0)
            $('#spnNavigation').html('<a href="javascript: history.go(-1)">Application Profile</a> >> ');
        else if (document.referrer.indexOf('LoanSelectionMenu.aspx') > 0)
            $('#spnNavigation').html('<a href="javascript: history.go(-1)">Loan Profile</a> >> ');
        else if (document.referrer.indexOf('GroupList.aspx') > 0)
            $('#spnNavigation').html('<a href="javascript: history.go(-1)">Group</a> >> ');
        else if (document.referrer.indexOf('ContactDetail.aspx') > 0)
            $('#spnNavigation').html('<a href="javascript: history.go(-1)">Client Profile</a> >> ');
        else
            $('#spnNavigation').html('<a href="javascript: history.go(-1)">Back</a> >> ');

        $('#spnNavigation').html($('#spnNavigation').html() + 'Client Profile');
    }
    function saveContact() {
        var email1 = true;
        var email2 = true;
        email1 = validateEmail($('#txtEmail').val());
        email2 = validateEmail($('#txtEmail2').val());

        if (email1 == false && email2 == false) {
            $.messager.alert('Morgan CRM', '<span style="color:red;font-weight:bold"> Both E-Mail Address are Invalid ! </span>');
            return;
        }
        else if (email1 == false && email2 == true) {
            $.messager.alert('Morgan CRM', '<span style="color:red;font-weight:bold">' + $('#txtEmail').val() + '</span> is not valid E Mail Address !!');
            return;
        }
        else if (email1 == true && email2 == false) {

            $.messager.alert('Morgan CRM', '<span style="color:red;font-weight:bold">' + $('#txtEmail2').val() + '</span> is not valid E Mail Address !!');
            return;
        }

        window.onbeforeunload = null;
        var txtFirstName = $('#txtFirstName').val();
        var txtMiddleName = $('#txtMiddleName').val();
        var txtSurName = $('#txtSurName').val();

        var txtDateBirth = $('#txtDateBirth').datebox('getValue');
        var txtDriverLicense = $('#txtDriverLicense').val();
        var txtMobile = $('#txtMobile').val();
        var txtHomePhone = $('#txtHomePhone').val();
        var txtEmail = $('#txtEmail').val();
        var txtEmail2 = $('#txtEmail2').val();
        var txtPostCode = $('#txtPostCode').val();
        if (txtPostCode.indexOf('_') > 0) {
            txtPostCode = txtPostCode.replace(/_/gi, "");

            if (txtPostCode.length > 0) {
                $.messager.alert('Morgan CRM', '<span style="color:red;font-weight:bold">' + '   ' + txtPostCode + '   ' + '</span> is not valid Postcode !!');
                return;
            }
            else
                txtPostCode = '';
        }
        var txtStreet = $('#txtStreet').val();
        var txtstreetno = $('#txtStreetNo').val();
        var txtSuburb = $('#txtSuburb').val();
        var txtResidenceLength = $('#txtResidenceLength').val();
        var cmbTitle = $('#cmbTitle').combobox('getValue');
        var cmbResidency = $('#cmbResidency').combobox('getValue');
        var cmbState = $('#cmbState').combobox('getValue');
        var cmbResidentialStatus = $('#cmbResidentialStatus').combobox('getValue');
        var cmbResidencePeriod = $('#cmbResidencePeriod').combobox('getValue');
        var cmbNumberofDependant = $('#cmbNumberofDependant').combobox('getValue');
        var txtMemo = $('#txtMemo').val();
        var Hoperator = $('#ContentPlaceHolder1_hdnusername').val();

        var unsubscribe_Ad = 0;
        if ($('#checkUnsub').is(":checked")) {
            unsubscribe_Ad = 1;
        }

        if (getQuerystring('contact_id', '') == '') {
            $.ajax({
                url: '/WebServices/ApplicationContact.ashx?method=ApplicationContactAdd',
                contentType: "application/json; charset=utf-8",
                data: {
                    'Title': cmbTitle, 'FirstName': txtFirstName, 'MiddleName': txtMiddleName, 'SurName': txtSurName, 'Citizenship': cmbResidency,
                    'DateBirth': DefaultformatDate(txtDateBirth), 'DriverLicense': txtDriverLicense, 'Mobile': txtMobile, 'HomePhone': txtHomePhone, 'Email': txtEmail,
                    'secondEmailAddress': txtEmail2, 'StreetNo': txtstreetno,
                    'Street': txtStreet, 'Suburb': txtSuburb, 'State': cmbState, 'PostCode': txtPostCode, 'app_ResidentialStatus': cmbResidentialStatus,
                    'ResidencePeriod': cmbResidencePeriod, 'ResidenceLength': txtResidenceLength, 'Unsubscribe_Ad': unsubscribe_Ad, 'Dependant': cmbNumberofDependant, 'Memo': txtMemo, 'Operator': Hoperator
                },
                success: function (data) {
                    $.each(eval(data.replace(/[\r\n]/, '')), function (i, rec) {
                        if (rec.ContactID != '' || rec.ContactID == null) {
                            $('#dlgSuccess').dialog('open');
                            var ConId = rec.ContactID;
                                <%Session["CurrentId"] = "'+ConId+'";%>
                            setTimeout(function () {
                                window.location.href = "/Pages/Contact/ContactDetail.aspx?contact_id=" + rec.ContactID;
                            }, 500);
                        }
                    });
                }
            });
        }
        else {
            $.ajax({
                url: '/WebServices/ApplicationContact.ashx?method=ApplicationContactEdit',
                contentType: "application/json; charset=utf-8",
                data: {
                    'ContactID': getQuerystring('contact_id', ''), 'Title': cmbTitle, 'FirstName': txtFirstName, 'MiddleName': txtMiddleName, 'SurName': txtSurName, 'Citizenship': cmbResidency,
                    'DateBirth': DefaultformatDate(txtDateBirth), 'DriverLicense': txtDriverLicense, 'Mobile': txtMobile, 'HomePhone': txtHomePhone, 'Email': txtEmail, 'secondEmailAddress': txtEmail2,
                    'StreetNo': txtstreetno, 'Street': txtStreet, 'Suburb': txtSuburb, 'State': cmbState, 'PostCode': txtPostCode, 'app_ResidentialStatus': cmbResidentialStatus,
                    'ResidencePeriod': cmbResidencePeriod, 'ResidenceLength': txtResidenceLength, 'Unsubscribe_Ad': unsubscribe_Ad, 'Dependant': cmbNumberofDependant, 'Memo': txtMemo, 'Operator': Hoperator
                },
                success: function () {

                    $('#lnkaddApp').linkbutton('enable');
                    $('#lnkaddClient').linkbutton('enable');
                    $('#dgContactHistory').datagrid('reload');
                    //txtFirstName = txtFirstName.charAt(0).toUpperCase() + txtFirstName.slice(1);
                    //$('#lblfirstName').html(txtFirstName);
                    //$('#ContentPlaceHolder1_ContactProfile_lbllastName').html(txtSurName.toUpperCase());
                    isMemoedited = false;
                    $('#dlgSuccess').dialog('open');
                    bindClientDetail();
                }
            });
        }
    }

    function OpenRemoveDupDialog() {
        $('#dlgRemoveDuplicate').dialog('open');
        var currentid = getQuerystring('contact_id', '');

        $('#lblcurrentContactID').text(currentid);
        $('#lblcurrentContactID').val(currentid);
    }
    function RemoveDuplicate() {
        $.ajax({
            url: '/WebServices/ApplicationContact.ashx?method=CheckContactID',
            data: { ContactID: $('#txtNewContactId').val() },
            success: function (rec) {
                if (rec == 'true') {
                    $.ajax({
                        url: '/WebServices/ApplicationContact.ashx?method=RemoveDuplicateClient',
                        data: { CurrentContactID: $('#lblcurrentContactID').val(), DupWithContactID: $('#txtNewContactId').val() },
                        success: function (data) {
                            //insert to contact_history
                            var desc = ' Remove the duplicated client= ' + $('#lblcurrentContactID').val() + ',to new client=' + $('#txtNewContactId').val();
                            var currentDate = new Date()
                            var day = currentDate.getDate()
                            var month = currentDate.getMonth() + 1
                            var year = currentDate.getFullYear()
                            var HistoryDate = month + "/" + day + "/" + year;

                            var currentTime = new Date()
                            var hours = currentTime.getHours()
                            var minutes = currentTime.getMinutes()
                            var seconds = currentTime.getSeconds();
                            var HistoryTime = hours + ':' + minutes + ':' + seconds;
                            var Action = 'Remove Duplicate';
                            // insert history record for Current Client
                            $.ajax({
                                url: "/WebServices/History.ashx?method=saveNewHistory",
                                data: {
                                    HistoryType: 'Contact', contactid: $('#lblcurrentContactID').val(), hdate: HistoryDate, htime: HistoryTime, action: Action,
                                    user: $('#ContentPlaceHolder1_hdnusername').val(), description: desc, appid: '0'
                                },
                                success: function (result) {

                                }
                            });
                            // insert history record for Duplicate Client

                            $.ajax({
                                url: "/WebServices/History.ashx?method=saveNewHistory",
                                data: {
                                    HistoryType: 'Contact', contactid: $('#txtNewContactId').val(), hdate: HistoryDate, htime: HistoryTime, action: Action,
                                    user: $('#ContentPlaceHolder1_hdnusername').val(), description: Description, appid: '0'
                                },
                                success: function (result) {
                                    $('#dgContactHistory').datagrid('reload');
                                    $('#dlgRemoveDuplicate').dialog('close');
                                    $.messager.alert('Morgan CRM', 'Duplicate client removed successfully');
                                    $('#txtNewContactId').val('');
                                    bindClientDetail();
                                }
                            });

                        }
                    });
                }
                else
                    $.messager.alert('Morgan CRM', "Contact ID:  " + $('#txtNewContactId').val() + " is not available !!");
            }
        });
    }

    function setFullName() {
        $('#txtFullName').val($('#txtFirstName').val() + ' ' + $('#txtMiddleName').val() + ' ' + $('#txtSurName').val());
        $('#dlgFullName').dialog('close')
        $('#txtEmail').focus();
    }

    function addNewApplication() {
        window.location.href = "/Pages/Application/ApplicationDetail.aspx?contact_id=" + getQuerystring('contact_id', '');
    }
    function formatDate(value, row) {
        var date = null;
        if (value == null)
            date = new Date();
        else
            date = new Date(value);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var month = '';
        switch (m) {
            case 1:
                month = 'Jan';
                break;
            case 2:
                month = 'Feb';
                break;
            case 3:
                month = 'Mar';
                break;
            case 4:
                month = 'Apr';
                break;
            case 5:
                month = 'May';
                break;
            case 6:
                month = 'Jun';
            case 7:
                month = 'Jul';
                break;
            case 8:
                month = 'Aug';
                break;
            case 9:
                month = 'Sep';
                break;
            case 10:
                month = 'Oct';
                break;
            case 11:
                month = 'Nov';
                break;
            case 12:
                month = 'Dec';
                break;
        }
        var d = date.getDate();
        return (d < 10 ? ('0' + d) : d) + ' ' + month + ' ' + y;
    }

    function au_formatter(value, row) {
        var date = (value === null) ? new Date() : new Date(value);
        $('#txtAge').val(ageCalculation(date) + ' years old');
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        return (d < 10 ? ('0' + d) : d) + '/' + (m < 10 ? ('0' + m) : m) + '/' + y;
    }
    function au_parser(s) {
        if (!s) return new Date();

        var ss = (s.split('/'));
        var d = new Number(ss[0]);
        var m = new Number(ss[1]);
        var y = new Number(ss[2]);

        if (!isNaN(d) && !isNaN(m) && !isNaN(y)) {
            return new Date(y, m - 1, d);
        }
        else {
            return new Date();
        }
    }

    function format_Date(value, row) {
        var date = null;
        if (value == null)
            date = new Date();
        else
            date = new Date(value);
        $('#txtAge').val(ageCalculation(date) + ' years old');
        alert(date);
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();

        return (d < 10 ? ('0' + d) : d) + '/' + (m < 10 ? ('0' + m) : m) + '/' + y;
    }


    function DefaultformatDate(value) {
        if (value == '')
            return '';
        dArr = value.split('/');
        return dArr[1] + '/' + dArr[0] + '/' + dArr[2];
    }

    function ageCalculation(dateString) {
        var today = new Date();
        var birthDate = new Date(dateString);
        var age = today.getFullYear() - birthDate.getFullYear();
        var m = today.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }
        return age;
    }
</script>
